/**
 * Looker  新闻整合系统
 * Author  :solosky <solosky772@qq.com>
 * File    :Data.js
 * Date    :August 13, 2009
 * License : Apache License 2.0 
 */

/**
 *  窗口包
 *  定义了类似windows 系统的窗口管理
 *  窗口的基本HTML代码如下
 <div class="window">
	<div class="window-frame">
    	<div class="window-head">
        	<span class="window-title">添加小工具</span>
            <span class="window-close">&nbsp;</span>
        </div>
        <div class="window-content">
			载入中，请稍后
        </div>
        <div class="window-button">
        	<input type="button" value="确定" class="input-yes"/>
            <input type="button" value="取消" class="input-no"/>
         </div>
    </div>
</div>
<div class="window-overlay"></div>
 */
 
 /**
  * 最基本的窗口类
  */
  var Window = function(options){
	  
	//基本配置
	this.options = {
		title:"新建窗口",//窗口标题
		width:400,		//高度
		height:300,		//宽度
		closable:true,	//可否关闭
		draggable:true,	//可否拖动
		modal:true,		//是否为模式窗口
		content:null,	//窗口内容
		url:null,		//窗口内容的地址,
        autoClose:0,    //多少毫秒后自动关闭，0为不关闭
		onLoad:null,	//如果设置了url属性载入成功后触发的事件
		onClose : null
	  };
	//窗口编号
	this.windowID = WindowHelper.getNextWindowID();
	//窗口基本html
	this.tpl = '<div class="window">'+
				'<div class="window-frame">'+
					'<div class="window-head">'+
					'</div>'+
					'<div class="window-content">'+
				   ' </div>'+
				'</div>'+
			'</div>';
	//经过jquery包装后的对象
	this.$window = null;
	//窗口是否显示
	this.isShow = false;
	
	$.extend(this.options,options);
	
	
	
	
	/////////////////////公开函数////////////////////////
	//显示窗口
	this.show = function(){
		if(!this.$window){
			this.render();						//渲染窗口
			WindowHelper.registerWindow(this);	//注册窗口
		}
		if(!this.isShow){
				if(this.options.modal)
					WindowHelper.showOverlay();
				this.$window.show();
				isShow = true;
                if(this.options.autoClose){
                    var self = this;
                    setTimeout(function(){self.close();},this.options.autoClose);
                }
		}
	};
	
	//关闭窗口
	this.close = function(){
		if($.isFunction(this.options.onClose)){
			if(this.options.onClose()==false)
				return;						
		}
		if(this.options.modal)
			WindowHelper.hideOverlay();
		WindowHelper.unregisterWindow(this);		//取消注册窗口
		var self = this;
		this.$window.fadeOut(800,function(){self.$window.remove()});
		//this.$window.remove();						//然后删除窗口
	};
	//设置自动关闭窗口
	this.autoClose = function(time){
		var self = this;
		setTimeout(function(){self.close();},time);
	};
	
	//返回窗口编号
	this.getWindowID = function(){
		return this.windowID;
	};
	//设置窗口内容
	this.setContent = function(html){
		this.$window.find(".window-content").html(html);
	};
	this.setTitle  = function(title){
		this.$window.find(".window-title").html(title);	
	};
	
	
	///////////////////私有函数///////////////////////////
	//显示载入提示
	this.showLoadTip = function(){
		this.$window.find(".window-content")
			.html('<div class="window-loading"><span><img src="./images/tab-loading.gif" /></span></div>');
	};
	//隐藏载入提示
	this.hideLoadTip = function(fn){
		if($.isFunction(fn))
			this.$window.find(".window-loading").fadeOut(fn);
		else
			this.$window.find(".window-loading").hide();
	};
	//渲染并输出
	this.render = function(){
		this.$window = $(this.tpl);
		this.renderFrame();			 		//渲染框架
		this.renderExtend();
		$("body").append(this.$window); 	//附加到文档中
		this.renderContent();				//渲染正窗口正文
	};
	//渲染基本框架
	this.renderFrame = function(){
		//添加windowID
		this.$window.attr("id",this.windowID);
		//计算相对位置
		var pageScroll = WindowHelper.getPageScroll();
		var pageSize   = WindowHelper.getPageSize();
		var left = (pageSize[0]-this.options.width)/2;
		var top  = 0;
		if(this.options.height!="auto")
			top  = (pageSize[3]-this.options.height)/2+pageScroll[1];
		else
			top  = (pageSize[3]-300)/2+pageScroll[1];
		//添加长宽属性
		this.$window.css({
			width  : this.options.width+"px",
			height : this.options.height=="auto" ? "auto" : this.options.height+"px",
			left   : left,
			top    : top,
			position : "absolute",
			display : "none"
 			});
		//添加标题属性
		this.$window.find(".window-head")
					.append('<span class="window-title">'
						+this.options.title+"</span>");
		//添加关闭按钮
		if(this.options.closable){
			var self = this;
			var closeButton = $('<span class="window-close">&nbsp;</span>')
							.click(function(){self.close();});
			this.$window.find(".window-head").append(closeButton);
		}
		//可否拖动
		if(this.options.draggable){
			this.$window.find(".window-head").css({cursor:"move"});
			this.$window.draggable({handle:".window-head",cursor:"move"});	
		}
		
	};
	//渲染其他东西，这个应该在子类重载，实现不同的渲染行为
	this.renderExtend = function(){};
	//渲染文本内容
	this.renderContent = function(){
		var $content = this.$window.find(".window-content");
		var self = this;
		//是否有content属性
		if(this.options.content){
			$content.html(this.options.content);
            //修复显示高度
            var pageScroll = WindowHelper.getPageScroll();
            var pageSize   = WindowHelper.getPageSize();alert($content.height());
            var top  = (pageSize[3]-$content.height())/2+pageScroll[1];
            this.$window.css({top:top});

			return;
		}
		//如果没有，检查是否有url属性，如果有开始载入
		if(this.options.url){
			var suc = function(data){
				//需要设置窗口的高为自动
				self.$window.css({height:"auto"});
				self.hideLoadTip(function(){
						$content.html(data);
						if($.isFunction(self.options.onLoad))
							self.options.onLoad(self);				 						  
				});
				
			};
			var err = function(data){
				var errMsg = $('<div>载入失败，请<a href="#">重试</a></div>')
							.find("a")
							.click(function(){
								self.renderContent();				
							});
							self.$window.find(".window-loading").html(errMsg);	 						  
			
			};
			//显示载入提示
			this.showLoadTip();
			//发起请求
			$.ajax({
				url      : this.options.url,
				dataType : "html",
				success  : suc,
				error    : err
			});
		}
		
	};
  };
 /**
  * 对话框类
  */
  var Dialog = function(options){
	  
	 Window.apply(this,arguments); 
	  	//基本配置
	this.options = {
		title:"新建窗口",//窗口标题
		width:400,		//高度
		height:300,		//宽度
		closable:true,	//可否关闭
		draggable:true,	//可否拖动
		modal:true,		//是否为模式窗口
		content:null,	//窗口内容
		url:null,		//窗口内容的地址
		onLoad:null,	//如果设置了url属性载入成功后触发的事件,
        autoClose:0,    //在多少秒后自动关闭
		buttons:[
				 {type:"ok",	title:"确定", callback:null},
				 {type:"cancel",title:"取消", callback:null}
				 ]
	  };

	  $.extend(this.options,options);
	  
	  ///////////////////////////////////////////////////////
	  //禁止按钮
	  //启用按钮...todo...
	  //需重新编写renderExtend函数
	  this.renderExtend = function(){
			this.renderButtons();
	  };
	  
	  //生成buttons
	  this.renderButtons = function(){
		   var $buttons = $('<div class="window-buttons"></div>');
		 var self     = this;
		for(var i=0; i<this.options.buttons.length; i++){
			var b = this.options.buttons[i];
			if(!b) continue;   ///BUG ..
			var t = $('<input type="button" value="'+b.title+'" />');
			if(b.type=="ok"){
				t.addClass("input-yes");
			}
			else if(b.type=="cancel")
				t.addClass("input-no");
			else{}
			//绑定事件
			if(b.type=="ok" || b.type=="cancel"){
				if($.isFunction(b.callback)){
                    //这里有点问题，在发生click事件时，这里的b.始终指向最后一个元素，需要使用匿名函数来保存
                    (function(){
                        var button = b;
                        t.click(function(){
                            if(button.callback()!==false)
							    self.close();
                        });
                    })();
				}else{
					t.click(function(){
						self.close();				 
					});	
				}	
			}else{
				if($.isFunction(b.callback))
				t.click(function(){
						b.callback();			 
				});	
			}
			//添加这个按钮至按钮层中
			$buttons.append(t);
		}
		//添加按钮层至窗体
		this.$window.find(".window-frame").append($buttons);	  
		  
	  };
	  
  };

 /**
  * 提示框类
  */
  var Message = function(options){
	  
	  Dialog.apply(this,arguments); 
	  	//基本配置
	this.options = {
		title:"消息",//窗口标题
		message:"消息正文", //消息正文
		width:400,		//高度
		height:300,		//宽度
		closable:true,	//可否关闭
		draggable:true,	//可否拖动
		modal:true,		//是否为模式窗口
        image:"ok",   //只能是info error ok notice,confirm,load
        buttons:[]
	  };
      this.messageTpl = '<div class="window-message">'+
                    '<div class="window-message-image">'+
                       '<img src="./images/message_{image}.gif" />'+
                    '</div>'+
                    '<div class="window-message-content">{content}</div><div class="clear"></div>'+
                  '</div>';

	  $.extend(this.options,options);
	  //////////////////////////////////////////////////////
	  //复写renderContent()
	  this.renderContent = function(){
          var t = this.messageTpl;
          t = t.replace("{image}",this.options.image);
          t = t.replace("{content}",this.options.message);
		  this.setContent(t);
          var $content = this.$window.find(".window-content");
          var pageScroll = WindowHelper.getPageScroll();
            var pageSize   = WindowHelper.getPageSize();
            var top  = (pageSize[3]-$content.height())/2+pageScroll[1]-100;
            this.$window.css({top:top+"px"});
	  };
	  //设置信息正文图片和信息
	  this.setMessage  = function(msg,image){
	      if(msg) this.$window.find(".window-message-content").html(msg);
		  if(image) this.$window.find(".window-message-image img").attr("src","./images/message_"+image+".gif");
	  };
  };
  Message.activeMessage = null;
  //为Message添加静态方法，方便调用
  Message.info = function(msg,title,image,onOK,autoClose,modal){
       var options = {
            title   : title||"提示信息",
            message : msg,
            autoClose : autoClose||0,
            image   : image||"OK",
            height  : "auto",
			modal   : modal,
            buttons :[
				 {type:"ok",	title:"确定", callback:onOK },
				 ]
       };
      var msg = new Message(options);
	   Message.activeMessage = msg;
      msg.show();
  };
  //确认框
  Message.confirm = function(msg,title,image,onOK,onCancel,modal){
        var options = {
            title   : title||"请选择",
            message : msg,
            autoClose :0,
            closable : false,
            image   : image||"confirm",
            height  : "auto",
			modal   : modal, 
            buttons :[
				 {type:"ok",	    title:"确定", callback:onOK },
                 {type:"cancel",	title:"取消", callback:onCancel },
				 ]
       };
      var msg = new Message(options);
	   Message.activeMessage = msg;
      msg.show();

  };
   
  /**
   * 窗口辅助工具
   */
   var WindowHelper = {
	   ////////////////////////////////////////////////////////////////////////////////
	   //覆盖图层的jquery引用
	   $overlay : null,
	   //下一个window编号
	   nextWindowID :1,
	   //所有窗口的引用
	   windowList : {},
	   
	   ////////////////////////////////////////////////////////////////////////////////
	   //显示覆盖图层
	   showOverlay : function(){
		   if(!this.$overlay)
		   		this.initOverlay();
			if(this.isShowOverlay())
				return;
			var pageSize = this.getPageSize();
			this.$overlay.css({
				width  : pageSize[0]+"px",
				height : pageSize[1]+"px"
			});
			this.$overlay.show();
	   },
	   //隐藏覆盖图层
	   hideOverlay : function(){
		 if(this.isShowOverlay()){
		 	this.$overlay.hide();
		 }
			
	   },
	   //初始化覆盖图层
	   initOverlay : function(){
		 this.$overlay = $('<div class="window-overlay"></div>');
		 //this.$overlay.click(function(){WindowHelper.hideOverlay();});
		 $("body").append(this.$overlay);
	   },
	   //检查当前覆盖图层是否已经显示
	   isShowOverlay : function(){
		 	return this.$overlay.css("display")=="none" ? false : true;  
	   },
	   //下一个window编号
	   getNextWindowID : function(){
		 	  return "window-"+(this.nextWindowID++);
	   },
	   //注册窗口对象
	   registerWindow : function(win){
		 this.windowList[ win.getWindowID()] = win;     
	   },
	   //取消注册窗口对象
	   unregisterWindow : function(win){
		 this.windowList[ win.getWindowID()] = null;     
	   },
	   //查找窗口对象
	   findWindow : function(windowID){
		   return this.windowList[windowID];
	   },
	   
	   //下面是其他人编写的函数，来自Jquery.lightBox插件，分别是返回页面大小和滚动大小的函数
	   /**
		 / THIRD FUNCTION
		 * getPageSize() by quirksmode.com
		 *
		 * @return Array Return an array with page width, height and window width, height
		 */
		getPageSize : function() {
			var xScroll, yScroll;
			if (window.innerHeight && window.scrollMaxY) {	
				xScroll = window.innerWidth + window.scrollMaxX;
				yScroll = window.innerHeight + window.scrollMaxY;
			} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
				xScroll = document.body.scrollWidth;
				yScroll = document.body.scrollHeight;
			} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
				xScroll = document.body.offsetWidth;
				yScroll = document.body.offsetHeight;
			}
			var windowWidth, windowHeight;
			if (self.innerHeight) {	// all except Explorer
				if(document.documentElement.clientWidth){
					windowWidth = document.documentElement.clientWidth; 
				} else {
					windowWidth = self.innerWidth;
				}
				windowHeight = self.innerHeight;
			} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
				windowWidth = document.documentElement.clientWidth;
				windowHeight = document.documentElement.clientHeight;
			} else if (document.body) { // other Explorers
				windowWidth = document.body.clientWidth;
				windowHeight = document.body.clientHeight;
			}	
			// for small pages with total height less then height of the viewport
			if(yScroll < windowHeight){
				pageHeight = windowHeight;
			} else { 
				pageHeight = yScroll;
			}
			// for small pages with total width less then width of the viewport
			if(xScroll < windowWidth){	
				pageWidth = xScroll;		
			} else {
				pageWidth = windowWidth;
			}
			arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
			return arrayPageSize;
		},
		/**
		 / THIRD FUNCTION
		 * getPageScroll() by quirksmode.com
		 *
		 * @return Array Return an array with x,y page scroll values.
		 */
		getPageScroll :function(){
			var xScroll, yScroll;
			if (self.pageYOffset) {
				yScroll = self.pageYOffset;
				xScroll = self.pageXOffset;
			} else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
				yScroll = document.documentElement.scrollTop;
				xScroll = document.documentElement.scrollLeft;
			} else if (document.body) {// all other Explorers
				yScroll = document.body.scrollTop;
				xScroll = document.body.scrollLeft;	
			}
			arrayPageScroll = new Array(xScroll,yScroll);
			return arrayPageScroll;
		}  
   };
   